package controller;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;

import model.Wiadomosc;

public class Client implements Runnable{

	private int port;
	private Socket s;
	private ObjectOutputStream output;
	private ObjectInputStream input;
	private String host, nazwa;
	
	@Override
	public void run() {
		String m1, m2;
		try 
		{
			s = new Socket(host, port);
			input = new ObjectInputStream(s.getInputStream());
			output = new ObjectOutputStream(s.getOutputStream());
			output.flush();
			System.out.println("Klient startuje na hoscie "+InetAddress.getLocalHost().getHostName());
			nazwa = InputOutput.weString("Podaj swoj nr BlaBla: ");
			output.writeObject(nazwa);
		
			do 
			{
				m1 = (String) input.readObject();
				System.out.println("\n" + "Dane odebrane od serwera: " + m1);
				m2 = InputOutput.weString("Podaj wiadomosc dla serwera: ");
				if(m2.contains("change_name"))
				{
					StringTokenizer st = new StringTokenizer(m1,";");
					st.nextToken();
					String imie = st.nextToken();
					nazwa = imie;
				}
				output.writeObject(nazwa + ": " + m2);
			} 
			while (!m2.equals("czesc"));
		
			output.close();
			input.close();
			s.close();
		} 
		catch (Exception e){System.out.println("Wyjatek klienta");e.printStackTrace();}
	}

	Client(String host_, int port_)
	{ 
		host = host_;
		port = port_; 
	}
	
	public static void main(String args[]) throws Exception
	{
		String s = InetAddress.getLocalHost().getHostName();
		Client k = new Client(s, 5000);
		Thread t = new Thread(k);
		t.start();
	}
}
